package parallels.servertech.client.commands;

import java.io.IOException;

import parallels.servertech.client.CommandContext;
import parallels.servertech.client.CommandHandler;
import parallels.servertech.common.Status;

public class AddHandler implements CommandHandler {
	private static final String COMMAND_NAME = "add";
	
	@Override
	public void handle(String[] args, CommandContext ctx) {
		if (args.length < 2) {
			ctx.getOut().printf("%s command has 2 args%n", COMMAND_NAME);
			return;
		}
		
		int left = Integer.parseInt(args[0]);
		int right = Integer.parseInt(args[1]);
		
		try {
			Status status = ctx.send(COMMAND_NAME, left, right);
			if (status != Status.SUCCESS) {
				String errMsg = ctx.receiveError();
				ctx.getOut().printf("%s command failed: %s%n", COMMAND_NAME, errMsg);
				return;
			}
			
			Integer sum = ctx.receive(input -> input.readInt());
			ctx.getOut().printf("sum: %d%n", sum);
		} catch (IOException ioe) {
			ctx.getOut().printf("failed to send: %s(%s)%n", ioe.getClass().getName(), ioe.getMessage());
		}
	}
}
